<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2022-12-14 10:52:25
 * @LastEditors: zzb
 * @LastEditTime: 2022-12-14 11:30:03
-->
<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2022-07-11 11:34:47
 * @LastEditors: zzb
 * @LastEditTime: 2022-12-14 10:45:48
-->
<template>
  <div class="app-container">
    <div class="content-wrap">
      <el-form
        :model="queryParams"
        size="small"
        ref="queryForm"
        :inline="true"
        label-width="68px"
        @submit.native.prevent
      >
        <el-form-item label="阅读时间">
          <!-- <el-date-picker v-model="queryParams.month" type="month" placeholder="选择月" value-format="yyyy-MM-dd" style="width: 130px;">
          </el-date-picker> -->
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-badge
            :value="channelIds.length"
            :max="10"
            class="item"
            v-if="false"
          >
            <el-button type="primary" size="small" @click="openChannel1"
              >选择栏目</el-button
            >
          </el-badge>
        </el-form-item>
        <el-form-item style="marginleft: 20px">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="small"
            :loading="exportLoading"
            @click="handleExport"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="statisticsList">
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="单位名称" align="center" prop="deptName" />
      <el-table-column label="公司要闻阅读数" align="center" prop="monthCount">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="false"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--  栏目列表 -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="dialogCloumn"
      width="450px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="bottom">
        <div class="bottom_l">
          <vxe-toolbar>
            <template #buttons>
              <vxe-radio-button
                v-model="value7"
                :label="true"
                v-if="false"
                :content="value7 ? '全部关闭' : '全部展开'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
              ></vxe-radio-button>

              <vxe-radio-button
                v-model="selectAll"
                :label="true"
                :content="!selectAll ? '全选' : '取消全选'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
                class="b-border"
              ></vxe-radio-button>

              <vxe-radio-button
                v-model="menuCheckStrictly"
                :label="true"
                :strict="false"
                content="父子联动"
                size="mini"
                class="b-border"
              ></vxe-radio-button>

              <!-- <vxe-checkbox v-model="menuCheckStrictly" content="父子联动"></vxe-checkbox> -->
            </template>
          </vxe-toolbar>
          <!-- <vxe-button @click="haldleClickSelectAll" size="mini">全选</vxe-button> -->
          <vxe-table
            v-if="dialogCloumn"
            row-key
            row-id="channelId"
            show-overflow
            ref="xTreeChannel"
            border="inner"
            :data="channelList"
            :tree-config="{
              children: 'children',
              transform: false,
              parentKey: 'parentId',
              line: true,
              iconOpen: 'el-icon-remove',
              iconClose: 'el-icon-circle-plus',
            }"
            :checkbox-config="{
              labelField: 'name',
              showHeader: false,
              checkStrictly: !menuCheckStrictly,
              checkRowKeys: channelIds,
              checkMethod,
              trigger: 'default',
            }"
            class="left-table"
          >
            <!-- 要用rightList.length判断。不能使用siterow -->
            <vxe-column type="checkbox" tree-node show-overflow>
              <template #title="{ row }">
                <span>
                  <span style="cursor: pointer; fontsize: 12px; color: #000"
                    >{{ siteRow.name }} 下的栏目列表
                  </span>
                  <span style="float: right; margin: 0 10px 0 0"
                    >已选择
                    {{ $refs.xTreeChannel.getCheckboxRecords().length }}
                    个栏目</span
                  >
                </span>
              </template>
              <template #default="{ row }">
                <span>
                  <span style="cursor: pointer; fontsize: 12px; color: #000">
                    {{ row.name }}</span
                  >
                </span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cacle">取 消</el-button>
        <el-button type="primary" @click="sureQuery">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { readAlertExport, readAlert } from "@/api/statistics/statistics";
import { getChannelListForTree } from "@/api/content/clounm";
import { mapState } from "vuex";
export default {
  name: "depRead",
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            },
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate(time) {
          //time = new Date()
          return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
          // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
          // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
          // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
        },
      },
      selectAll: false,
      loading: false,
      menuCheckStrictly: false,
      // 栏目 对话框
      dialogCloumn: false,
      //全部展开 全部关闭
      value7: false,
      // 统计出的结果
      statisticsList: [],
      total: 0,
      //选中的栏目
      channelIds: [],

      channelIdsTotal: 0,

      channelList: [],
      exportLoading: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        // dayNum: 360,
        channelIds: "2153,2154",
      },

      title: "",
      dialogCloumn: false,
    };
  },

  components: {},

  computed: {
    ...mapState({
      siteRow: (state) => state.column.siteRow,
    }),
    // 默认时间
    timeDefault() {
      let date = new Date();
      // 通过时间戳计算
      let defalutStartTime = date.getTime() - 7 * 24 * 3600 * 1000; // 转化为时间戳
      let defalutEndTime = date.getTime();
      let startDateNs = new Date(defalutEndTime);
      let endDateNs = new Date(defalutEndTime);
      // 月，日 不够10补0
      defalutStartTime =
        startDateNs.getFullYear() +
        "-" +
        (startDateNs.getMonth() + 1 >= 10
          ? startDateNs.getMonth() + 1
          : "0" + (startDateNs.getMonth() + 1)) +
        "-" +
        "01";
      defalutEndTime =
        endDateNs.getFullYear() +
        "-" +
        (endDateNs.getMonth() + 1 >= 10
          ? endDateNs.getMonth() + 1
          : "0" + (endDateNs.getMonth() + 1)) +
        "-" +
        (endDateNs.getDate() >= 10
          ? endDateNs.getDate()
          : "0" + endDateNs.getDate());
      return [defalutStartTime, defalutEndTime];
    },
  },

  mounted() {
    // this.dateRange = this.timeDefault;
    const end = new Date();
    const start = end.getTime() - 3600 * 1000 * 24 * 7;

    this.dateRange = [
      this.parseTime(start, "{y}-{m}-{d}"),
      this.parseTime(end, "{y}-{m}-{d}"),
    ];
    console.log(
      "🚀 ~ file: readAlert.vue:225 ~ mounted ~  this.dateRange",
      this.dateRange
    );
    this.getList();
  },

  watch: {
    // siteRow: {
    //   handler(val, oldVal) {
    //     this.getChannelList();
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    value7(value) {
      if (value) {
        this.$refs.xTreeChannel.setAllTreeExpand(true);
      } else {
        this.$refs.xTreeChannel.clearTreeExpand();
      }
    },
    selectAll(value) {
      if (value) {
        this.menuCheckStrictly = true;
        this.$nextTick(() => {
          this.dialogCloumn && this.$refs.xTreeChannel.setAllCheckboxRow(true);
        });
      } else {
        this.dialogCloumn && this.$refs.xTreeChannel.setAllCheckboxRow(false);
        this.$nextTick(() => {
          this.menuCheckStrictly = false;
        });
      }
    },
  },

  methods: {
    openChannel1() {
      this.dialogCloumn = true;
      this.title = "选择栏目";
    },
    getMonth() {
      let month = new Date().getMonth() + 1;
      this.queryParams.month = month >= 10 ? month : "0" + month;
    },
    // 获取统计列表
    getList() {
      console.log("this.dateRange: ", this.dateRange);
      if (!this.dateRange) {
        this.msgError("请选择阅读时间");
        return;
      }
      this.loading = true;
      this.queryParams.startDay = this.dateRange[0];
      this.queryParams.endDay = this.dateRange[1];
      readAlert(this.queryParams).then((res) => {
        this.statisticsList = res.data;
        this.loading = false;
      });
    },
    //获取栏目列表
    getChannelList() {
      getChannelListForTree({ siteId: this.siteRow.siteId })
        .then((res) => {
          this.value7 = false;
          this.channelList = this.handleTree(res.data, "channelId").filter(
            (item) => item.parentId == this.siteRow.siteId
          );
        })
        .then(() => {});
    },
    //确认  统计栏目列表
    sureQuery() {
      let selection = this.$refs.xTreeChannel.getCheckboxRecords();
      this.channelIdsTotal = selection.length;

      this.channelIds = selection.map((item) => item.channelId);
      console.log(
        "🚀 ~ file: depRead.vue:235 ~ sureQuery ~ this.channelIds",
        this.channelIds
      );
      this.cacle();
    },
    handleQueryUserName(row) {
      this.$emit("changeActiceName", "username");

      this.$store.dispatch("statistics/setChannelIds", [row.channelId]);
      // this.$emit("changeComponent", "ArticleDetail");
    },
    handleQueryChannel(row) {
      this.$store.dispatch("statistics/setChannelIds", [row.channelId]);
      this.$emit("changeComponent", "ArticleDetail");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.channelIds = this.channelIds.join(",");
      this.getList();
    },
    /**导出各单位阅读量 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有参数数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return readAlertExport(queryParams);
        })
        .then((response) => {
          this.resolveBlob(
            response,
            "xlsx",
            `各单位${queryParams.month}阅读量`
          );
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    cacle() {
      this.dialogCloumn = false;
    },
    //复选框方法，disable第一行的
    checkMethod({ row }) {
      return row.channelId && row.channelId != this.channelId;
    },
  },
};
</script>

<style scoped lang="scss">
.bottom {
  display: flex;
  // height: 500px;
  height: 50vh;
  .bottom_l {
    // overflow: auto;
    flex: 1;
    height: 100%;
    // background: #fffbf0 !important;
    display: flex;
    flex-direction: column;
    .left-table {
      flex: 1;
      height: 0;
      overflow: overlay;
      overflow: auto;
    }
  }
}
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
</style>
